<?php

class SaleModel extends Model
{
	
	
	
	public $error = '';
    //退款
    public function refund($sale_id, $site_id, $thnum)
    {
        $sale = $this->where(array('id' => $sale_id, 'site_id' => $site_id, 'pay_status' => 1))->find();
        if (!$sale) {
            return false;
        }
        if ($sale['num'] < $thnum) {
            return false;
        } else {
            $udata['num'] = $sale['num'] - $thnum;
            if($udata['num'] < 0){
                return false;
            }else{
                if($udata['num'] > 0){
                    //部分退款
                    $udata['pay_status'] = 2;
                }else{
                    //全部退款
                    $udata['pay_status'] = 3;
                }
                $udata['total'] = $sale['total'] - $sale['price']*$thnum;
                $udata['thnum'] = $thnum;
                $ret = $this->where(array('id' => $sale_id)) -> data($udata) -> save(); 
                
				if($ret !== false){
					
                    // alicext 不退款到会员账户余额，通过微信原路退款
                    $orderdb = M('Order');
                    $this->orderinfo = $orderdb -> where(array('id' => $sale['order_id'])) -> find();
                    $payment = M('Payment') -> where(array('status' => 1, 'site_id' => __SITEID__, 'id' => $this->orderinfo['payment_id'])) -> find();
                    import ( '@.ORG.Payment.'.$payment['classname'] );
                    $affclass = $payment['classname'];
                    if($affclass == "Wxpay"){
                        $aff = new $affclass(__SITEID__);
						
						$refund_fee = $sale['price']*$thnum > $this->orderinfo['total'] ? $this->orderinfo['total']: $sale['price']*$thnum;
						$fee_=$this->fee_($sale);
						if($fee_!=0&&$sale['status']==1){
					
						$this->get_fee($sale,$fee_);
						
						$fee_=0;	
						}
						
					
						
                        $rmsg = $aff -> refund($sale_id,($sale['price']*$thnum)+$fee_);
                        
                        $member = M("member")->where(array('id'=>$sale['member_id']))->find();
                        // $msg = "退款通知\n您得订单:".$this->orderinfo['ordernumber']."成功原路退款\n退款金额:".$sale['price']*$thnum."元";
                            // sendWXMsg("oSWvqs7Dp0HhbiyRRjXVfEn4iaCY",json_encode($member));
                        if($rmsg['return_code'] == "SUCCESS" && $rmsg['result_code'] != 'FAIL'){
                            // 通知用户退款成功
                            sendWXMsg($member['openid'],$msg);
                            $content = array(); 
                            $content[0] = array("title" =>"退款通知", 
                             "description" =>"您得订单:".$this->orderinfo['ordernumber']."成功原路退款\n"
                             ."退款金额:".(($sale['price']*$thnum)+$fee_)."元", 
                             // "picurl" =>"http://".$_SERVER['HTTP_HOST']."/Public".$sale['img_url'], 
                             "url" =>U('Member/Order/read',array('id' => $this->orderinfo['id']), true, false, true),
                             );
                            sendWXNews($member['openid'], $content);
                            //取消分成 
							$maldb = D('Member_account_log');
                            $maldb -> cancel($sale['order_id'], $sale['product_id'], $sale['attr'], $thnum);
										
							if($sale['member_id']==11||$sale['member_id']==1){
								
							
							$this->deduction($sale);
							}
                            return true;
                        }else{
							
							
							//没有事务机制，错误后修改记录为原来的状态
							$this->where(array('id' => $sale_id)) -> data($sale) -> save(); 
							if($rmsg['result_code'] == 'FAIL'){
								$this -> error = $rmsg['err_code_des'];
							}
							
                            return false;
                        }
                    }else{
                        // 正确之后退款到会员账户
						$order=M('Order')->where(' id = '.$sale['order_id'])->find();
				
						if($order['integral_pay']>0){
					
						D('Points')->refund($sale_id);
						}else{
						$maldb = D('Member_account_log');
    
                        $maldb -> cancel($sale['order_id'], $sale['product_id'], $sale['attr'], $thnum);
    
                        $ordernumber = M('Order') -> where(array('id' => $sale['order_id'])) -> getField('ordernumber');
                        $maldb -> change($sale['thnum']*$sale['price'], $sale['member_id'], '订单：'.$ordernumber.'退款');	
						}
						
						
				    }
					D('Points')->deduction($sale['id']);
                    return true;
                }else{
                    return false;
                }
            }
		}
        return true;
    }
	//计算当前供货商当前销售单的运费
	//@sale  传当前sale数据
	//return 运费的金额
	public function fee_($sale){
	
	$dao=M('Sale');
	$list=$dao->where(array('order_id'=>$sale['order_id'],'supplier_id'=>$sale['supplier_id']))->select();
	$fee = 0;
	foreach($list as $k=>$v){
	if ($v['pay_status'] != 3) {
   	return 0;
    }
	$price+=($v['price']*$v['buy_num']);
	}
	if($fee==0){
	$fee=M('Order_supplier')->where(' order_id = '.$sale['order_id'].' and price = '.$price)->getField('shipping_fee');
	}
	return $fee;	
	}
	//当运费没有给用户的时候，退给商家
	//@sale  传当前sale数据
	//@fee   运费金额
	//无返回
	public function get_fee($sale,$fee){
		$order=M('Order')->where('id = '.$sale['order_id'])->find();
		
		if($fee==0){
			return false;
		}
		$s_member=M('Supplier')->where(' id = '.$sale['supplier_id'])->find();
		$s_member=M('Member')->where(' id = '.$s_member['member_id'])->find();
		$data['site_id']=__SITEID__;
		$data['order_id']=$sale['order_id'];
		$data['order_sn']=$order['ordernumber'];
		$data['remark']=$order['ordernumber'].'退货，运费退还商家。';
		$data['member_id']=$s_member['id'];
		$data['dateline']=time();
		$data['changenum']=$fee;
		$data['pdstatus']=4;
		$data['status']=1; 
		$data['total']=$s_member['money']+$fee; 
		
		$res=M('Member')->where(' id = '.$s_member['id'])->save(array('money'=>($s_member['money']+$fee)));
		
		if($res){
		M('Member_account_log')->add($data);
		}
		
		
	}
    public function ourtotal(){
        $date=array();
        $start=strtotime(date('Y-m-d'));
        $end=strtotime(date('Y-m-d'))+86400;
        $map['create_time']=array('between',array($start,$end));
        $map['pay_status']=1;
        $day_one=$total=D('Sale')->where($map)->sum('total');
        if(!$day_one)$day_one=0;else $day_one=intval($day_one);
        $start=$start-86400;
        $end=$end-86400;
        $map['create_time']=array('between',array($start,$end));
        $day_two=$total=D('Sale')->where($map)->sum('total');
        if(!$day_two)$day_two=0;else $day_two=intval($day_two);
        $start=$start-86400;
        $end=$end-86400;
        $map['create_time']=array('between',array($start,$end));
        $day_three=$total=D('Sale')->where($map)->sum('total');
        if(!$day_three)$day_three=0;else $day_three=intval($day_three);
        $start=$start-86400;
        $end=$end-86400;
        $map['create_time']=array('between',array($start,$end));
        $day_four=$total=D('Sale')->where($map)->sum('total');
        if(!$day_four)$day_four=0;else $day_four=intval($day_four);
        $start=$start-86400;
        $end=$end-86400;
        $map['create_time']=array('between',array($start,$end));
        $day_five=$total=D('Sale')->where($map)->sum('total');
        if(!$day_five)$day_five=0;else $day_five=intval($day_five);
        $start=$start-86400;
        $end=$end-86400;
        $map['create_time']=array('between',array($start,$end));
        $day_six=$total=D('Sale')->where($map)->sum('total');
        if(!$day_six)$day_six=0;else $day_six=intval($day_six);
        $start=$start-86400;
        $end=$end-86400;
        $map['create_time']=array('between',array($start,$end));
        $day_seven=$total=D('Sale')->where($map)->sum('total');
        if(!$day_seven)$day_seven=0;else $day_seven=intval($day_seven);

        $arr=array($day_seven,$day_six,$day_five,$day_four,$day_three,$day_two,$day_one);
        for ($i=0;$i++;$i>6){
            array_unshift($date,date('Y-m-d',time()-$i*86400));
        }
        $date=array(self::day(time()-6*86400),self::day(time()-5*86400),self::day(time()-4*86400),self::day(time()-3*86400),self::day(time()-2*86400),self::day(time()-1*86400),self::day(time()));
//        for($i=0;$i++;$i>7){
//            $start=strtotime(date('Y-m-d'))-86400*$i;
//            $end=strtotime(date('Y-m-d'))-86400*($i-1);
//            $map['create_time']=array('between',array($start,$end));
//            $map['pay_status']=1;
//            $total=D('Sale')->where($map)->sum('total');
//            if($total!=0){
//                array_push($arr,$total);
//            }else{
//                array_push($arr,0);
//            }
//            array_push($date,date('Y-m-d',$start));
//        }
        if(D('Faker')->where('id = 1')->getfield('status')==1){
            $mylist=D('Faker')->where('id = 1')->find();
            $arr=array(
                intval($mylist['first']),
                intval($mylist['second']),
                intval($mylist['third']),
                intval($mylist['forth']),
                intval($mylist['fifth']),
                intval($mylist['sixth']),
                intval($mylist['seventh'])
            );
        }
        $dayreturn['arr'] = json_encode($arr);
        $dayreturn['date'] = json_encode($date);
        return($dayreturn);
    }
	
	
	
    public function day($i){
        return date('Y-m-d',$i);
    }
	public function deduction($date){
		
		
		$member_id=M('Supplier')->where(' id = '.M('Product')->where(' id = '.$date['product_id'])->getField('supplier_id'))->find();
		
		$member=M('Member')->where(' id = '.$member_id['member_id'])->find();
		
	
		
		$member_acc=M('Member_account_log')->where(' sale_id = '.$date['id'])->find();	
		if($member_acc){
		unset($member_acc['id']);	
		unset($member_acc['attr']);	
		$member_acc['pdstate']=0;
		$member_acc['remark']='订单\n'.$member_acc['order_sn'].'退款';
		$member_acc['dateline']=time();
		M('Member')->where(' id = '.$member['id'])->save(array('money'=>($member_acc['changenum'])));
		M('Member_account_log')->add($member_acc);
		
		}
		
	}
	
	
    public function newtotal(){
        $daylist = D('Sale')->where('pay_status = 1')
            ->group("FROM_UNIXTIME(`create_time` + 8 * 3600,'%Y-%m-%d')")
            ->field("sum(total) as sum,FROM_UNIXTIME(`create_time` + 8 * 3600,'%Y年%m月%d日') as date")
            ->select();
        $dayarr = array();
        $daydate = array();
        foreach ($daylist as $key => $val) {
            $dayarr[] = intval($val['sum']); // 单日分数
            $daydate[] = $val['date']; // 日期
        }
        $dayreturn['arr'] = json_encode($dayarr);
        $dayreturn['date'] = json_encode($daydate);
        return $dayreturn;
    }
}